package com.lgCore.nettyCocurrent;/**
 * Created by by on 2020/11/13 10:35
 */

import com.lgCore.common.LocalSession;
import com.lgCore.common.SessionManger;
import com.lgCore.common.UserDTO;
import com.lgCore.protoModel.ProtoMsg;
import com.lgCore.util.ProtoByteUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;

/**
 * 任务异步执行
 *
 * @program: sxreader_rpc
 * @author: ligang
 * @create: 2020-11-13 10:35
 */
public class LoginCallable implements Callable<Boolean> {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginCallable.class);
    private ChannelHandlerContext ctx;
    private ProtoMsg.LoginRequest loginRequest;
    private ChannelHandler channelHandler;

    public LoginCallable(ChannelHandlerContext ctx, ProtoMsg.LoginRequest loginRequest, ChannelHandler channelHandler) {
        this.ctx = ctx;
        this.loginRequest = loginRequest;
        this.channelHandler = channelHandler;
    }

    @Override
    public Boolean call() throws Exception {
        //登录默认通过
        //装载信息
        LocalSession session = new LocalSession(ctx.channel());
        UserDTO user = new UserDTO();
        user.setUserName(loginRequest.getUserName());
        session.setUser(user);
        session.setLogin(true);
        SessionManger.addLocalSession(session);
        //数据放到管道上，可共享
        ctx.channel().attr(LocalSession.SESSION_KEY).set(session);
        /**
         * 通知客户端：登录成功
         */
        ProtoMsg.Message.Builder message = ProtoMsg.Message.newBuilder();
        //登录返回
        ProtoMsg.LoginResponse.Builder loginResponse = ProtoMsg.LoginResponse.newBuilder();
        loginResponse.setClientId(session.getClientId());
        loginResponse.setCode("200");
        loginResponse.setResult(true);
        loginResponse.setType(ProtoMsg.HeadType.LOGIN_RESPONSE);
        message.setLoginResponse(loginResponse.build());
        ctx.channel().writeAndFlush(ProtoByteUtil.protoToByte(message));

//        if (r) {
//            ctx.pipeline().remove(LoginRequestHandler.this);
//            log.info("登录成功:" + session.getUser());
//
//        } else {
//            SessionManger.inst().closeSession(ctx);
//            log.info("登录失败:" + session.getUser());
//        }
        ctx.pipeline().remove(channelHandler);
        LOGGER.info("登录成功:" + session.getUser());
        return true;
    }
}
